package cn.iocoder.yudao.module.picturebook.service.DashboardData;

import cn.iocoder.yudao.module.picturebook.controller.admin.allData.vo.BookCategory;
import cn.iocoder.yudao.module.picturebook.controller.admin.allData.vo.DashboardData;
import cn.iocoder.yudao.module.picturebook.controller.admin.allData.vo.Statistics;
import cn.iocoder.yudao.module.picturebook.controller.admin.allData.vo.TrendData;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.bookgather.BookGatherDO;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.category.CategoryDO;
import cn.iocoder.yudao.module.picturebook.dal.mysql.book.BookMapper;
import cn.iocoder.yudao.module.picturebook.dal.mysql.bookgather.BookGatherMapper;
import cn.iocoder.yudao.module.picturebook.dal.mysql.category.CategoryMapper;
import cn.iocoder.yudao.module.picturebook.dal.mysql.classcheckin.ClassCheckinMapper;
import cn.iocoder.yudao.module.picturebook.dal.mysql.classes.ClassesMapper;
import cn.iocoder.yudao.module.picturebook.dal.mysql.readingrecord.ReadingRecordMapper;
import cn.iocoder.yudao.module.picturebook.dal.mysql.user.PBUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.TextStyle;
import java.util.*;

@Service
@Validated
@Slf4j
public class DashboardDataServiceImpl implements DashboardDataService {
    @Resource
    private BookMapper bookMapper;
    @Resource
    private ReadingRecordMapper readingRecordMapper;
    @Resource
    private ClassCheckinMapper classCheckinMapper;
    @Resource
    private ClassesMapper classesMapper;
    @Resource
    private PBUserMapper userMapper;
    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private BookGatherMapper bookGatherMapper;
    // ... existing code ...
    /*获取数据面板上的所有数据*/
    @Override
    //刷新redis缓存
    public DashboardData getAllData() {
        DashboardData dashboardData = new DashboardData();

        try {
            //第一步：获取基础统计数据（数据卡片区）
            Statistics statistics = new Statistics();
            //统计所有绘本的数量
            try {
                statistics.setTotalBooks(Math.toIntExact(bookMapper.selectCount()));
            } catch (Exception e) {
                statistics.setTotalBooks(0);
            }

            //统计活跃用户数量(获取近三天的阅读记录，记得去重用户id)
            //获取当前时间
            LocalDate now = LocalDate.now();
            //获取近三天的时间
            LocalDate threeDaysAgo = now.minusDays(3);
            //根据时间获取
            int readingRecordByThree = 0;
            try {
                readingRecordByThree = readingRecordMapper.getReadingRecordByThree(threeDaysAgo, now);
            } catch (Exception e) {
                // 出现异常时使用默认值
            }
            statistics.setActiveUsers(readingRecordByThree);

            //获取今日阅读人数
            int todayReads = 0;
            try {
                todayReads = readingRecordMapper.getTodayCountByTime(now);
            } catch (Exception e) {
                // 出现异常时使用默认值
            }
            statistics.setTodayReads(todayReads);

            //获取今日打卡数量
            int todayCheckins = 0;
            try {
                todayCheckins = classCheckinMapper.getTodayCount(now);
            } catch (Exception e) {
                // 出现异常时使用默认值
            }
            statistics.setTodayCheckins(todayCheckins);

            //统计班级总数
            try {
                statistics.setTotalClasses(Math.toIntExact(classesMapper.selectCount()));
            } catch (Exception e) {
                statistics.setTotalClasses(0);
            }

            //统计注册总人数
            try {
                statistics.setTotalRegistrations(Math.toIntExact(userMapper.selectCount()));
            } catch (Exception e) {
                statistics.setTotalRegistrations(0);
            }

            dashboardData.setStats(statistics);

            //获取柱状图
            TrendData trendData = new TrendData();
            trendData.setTimeDimension("week");
            List<String> timeLabels = new ArrayList<>();
            //获取从今日往前数一共七天的星期数
            for (int i = 0; i < 7; i++) {
                LocalDate date = LocalDate.now().minusDays(i);
                DayOfWeek dayOfWeek = date.getDayOfWeek();
                // TextStyle.SHORT 表示短格式（"周一"），FULL表示"星期一"
                String weekName = dayOfWeek.getDisplayName(TextStyle.SHORT, Locale.CHINA);
                timeLabels.add(weekName);
            }
            //反序一下
            Collections.reverse(timeLabels);
            trendData.setTimeLabels(timeLabels);

            //获取每天的打卡人数没有就填0
            List<Integer> values = new ArrayList<>();
            for (int i = 0; i < 7; i++) {
                LocalDate date = LocalDate.now().minusDays(i);
                Integer todayCount = 0;
                try {
                    todayCount = classCheckinMapper.getTodayCount(date);
                } catch (Exception e) {
                    // 出现异常时使用默认值
                }
                values.add(todayCount != null ? todayCount : 0);
            }
            //反序
            Collections.reverse(values);
            trendData.setValues(values);
            dashboardData.setTrendData(trendData);

            //获取中文饼状图
            List<BookCategory> chineseCategories = new ArrayList<>();
            try {
                //先获取所有中文分类
                List<CategoryDO> chineseCategoriesDO = categoryMapper.selectChinese();
                if (chineseCategoriesDO != null) {
                    //获取每个分类下的绘本数量
                    for (CategoryDO chineseCategoryDO : chineseCategoriesDO) {
                        if (chineseCategoryDO != null) {
                            BookCategory bookCategory = new BookCategory();
                            bookCategory.setName(chineseCategoryDO.getCategoryName());
                            List<BookGatherDO> bookGatherDOS = bookGatherMapper.selectListByCategoryId(chineseCategoryDO.getCategoryId());
                            //统计每天绘本集的数量
                            int count = 0;
                            if (bookGatherDOS != null) {
                                for (BookGatherDO bookGatherDO : bookGatherDOS) {
                                    if (bookGatherDO != null && bookGatherDO.getTotal() != null) {
                                        try {
                                            count += Integer.parseInt(bookGatherDO.getTotal());
                                        } catch (NumberFormatException e) {
                                            // 解析失败时跳过该值
                                        }
                                    }
                                }
                            }
                            bookCategory.setValue(count);
                            chineseCategories.add(bookCategory);
                        }
                    }
                }
            } catch (Exception e) {
                // 出现异常时使用空列表
            }
            dashboardData.setChineseCategories(chineseCategories);

            //获取英文饼状图
            List<BookCategory> englishCategories = new ArrayList<>();
            try {
                List<CategoryDO> englishCategoryDOs = categoryMapper.selectEnglish();
                if (englishCategoryDOs != null) {
                    for (CategoryDO categoryDO : englishCategoryDOs) {
                        if (categoryDO != null) {
                            BookCategory bookCategory = new BookCategory();
                            bookCategory.setName(categoryDO.getCategoryName());
                            List<BookGatherDO> bookGatherDOS = bookGatherMapper.selectListByCategoryId(categoryDO.getCategoryId());
                            int count = 0;
                            if (bookGatherDOS != null) {
                                for (BookGatherDO bookGatherDO : bookGatherDOS) {
                                    if (bookGatherDO != null && bookGatherDO.getTotal() != null) {
                                        try {
                                            count += Integer.parseInt(bookGatherDO.getTotal());
                                        } catch (NumberFormatException e) {
                                            // 解析失败时跳过该值
                                        }
                                    }
                                }
                            }
                            bookCategory.setValue(count);
                            englishCategories.add(bookCategory);
                        }
                    }
                }
            } catch (Exception e) {
                // 出现异常时使用空列表
            }
            dashboardData.setEnglishCategories(englishCategories);
        } catch (Exception e) {
            // 出现任何未处理的异常，返回空的DashboardData对象
            return new DashboardData();
        }

        return dashboardData;
    }
// ... existing code ...

}
